<template>
	<view class="addjiancha">
		<headertop :title="pagetitle" str1="oridei" :back1="back1"></headertop>
		<view class="addjianchaback">

		</view>
		<view class="" :style="{'margin-top':statusBarHeight+'px','width':'100%','height':barHeight+'px'}">
		</view>
		<view class="jianchaxm">
			<view class="cardform">
				<view class="center">
					<view class="lineform">
						<view class="lefttext">
							<span style="color:#F53F3F;">*</span>
							<span>就诊类型：</span>
						</view>
						<view class="rightcontent" @click="open('就诊类型')">
							<view style="display: flex;align-items: center;" v-if="!numtext(formData.is_first)">
								<input type="text" :disabled="true" :disblead="true" v-model="formData.is_first"
									placeholder="请选择就诊类型" />
								<image :src="_static('/images/Frjt.png')" class="rightarrow" mode="">
								</image>
							</view>

							<span v-else>{{numtext(formData.is_first)}}</span>
						</view>
					</view>
					<view class="lineform">
						<view class="lefttext">
							<span style="color:#F53F3F;">*</span>
							<span>就诊日期：</span>
						</view>
						<view class="rightcontent" @click="open('就诊日期')">
							<image :src="_static('/images/riliicon.png')" class="righticon" mode="">
							</image>
							<span style="font-size: 28rpx;color: #86909C;">{{formData.visit_time||'请选择时间'}} </span>
						</view>
					</view>
					<view class="lineform">
						<view class="lefttext">
							<span>医院：</span>
						</view>
						<view class="rightcontent">
							<input type="text" v-model="formData['hospital']" placeholder="请输入医院" />
						</view>
					</view>
					<view class="lineform">
						<view class="lefttext">
							<span style="color:#F53F3F;">*</span>
							<span>诊断结果：</span>
						</view>
						<view class="rightcontent">
							<input type="text" v-model="formData['diagnosis_result']" placeholder="请输入诊断结果" />
						</view>
					</view>
					<view class="lineform">
						<view class="lefttext">
							<span>主诉：</span>
						</view>
						<view class="rightcontent">
							<input type="text" v-model="formData['zhusu']" placeholder="请输入主诉" />
						</view>
					</view>
					<view class="lineform">
						<view class="lefttext">
							<span>现病史：</span>
						</view>
						<view class="rightcontent">
							<input type="text" v-model="formData['xianbingshi']" placeholder="请输入现病史" />
						</view>
					</view>
					<view class="lineform">
						<view class="lefttext">
							<span>既往史：</span>
						</view>
						<view class="rightcontent">
							<input type="text" v-model="formData['jiwangshi']" placeholder="请输入既往史" />
						</view>
					</view>
					<view class="lineform">
						<view class="" style="width: 100%;overflow: hidden;margin-top: 24rpx;">
							<view class="lefttext">
								添加照片：
							</view>
							<view class="images">

								<view class="image" v-for="(item,index) in images" :key="index">
									<image :src="item" mode=""></image>
									<image :src="_static('/images/删除.png')" @click="shanchu(images,index)"
										class="remivon" mode=""></image>
								</view>
								<image :src="_static('/images/Group 11728@2x(1).png')" @click="uploadImage('images')"
									class="imageadd" mode="" v-if="images.length!=3">
								</image>
							</view>
							<view class="msgtext">
								支持格式：JPG、PNG、单个文件不能超过2m
							</view>
						</view>
					</view>
					<view class="lineform">
						<view class="" style="width: 100%;overflow: hidden;margin-top: 24rpx;">
							<view class="lefttext">
								用药照片：
							</view>
							<view class="images">

								<view class="image" v-for="(item,index) in medicine_images" :key="index"
									v-if="medicine_images">
									<image :src="item" mode=""></image>
									<image :src="_static('/images/删除.png')" @click="shanchu(medicine_images,index)"
										class="remivon" mode=""></image>
								</view>
								<image :src="_static('/images/Group 11728@2x(1).png')"
									@click="uploadImage('medicine_images')" class="imageadd"
									v-if="medicine_images.length!=3" mode=""></image>
							</view>
							<view class="msgtext">
								支持格式：JPG、PNG、单个文件不能超过2m
							</view>
						</view>
					</view>
					<view class="lineform" style="border: none;">
						<view class="" style="width: 100%;overflow: hidden;margin-top: 24rpx;">
							<view class="lefttext">
								备注：
							</view>
							<view class="textsform">
								<textarea placeholder="请输入内容" cursor-spacing="100" v-model="formData.remark"
									class="text1" id="" cols="30" rows="10"></textarea>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		<up-popup :show="show" mode="bottom">
			<view class="xuanxiang">
				<view class="tt" style="margin-left: 30rpx;color: #888;" @click="show=false">
					取消
				</view>
				<view class="tt" style="font-weight: 600;">
					请选择{{popuStr}}
				</view>
				<view class="tt" style="margin-right: 30rpx;color: #0077BE;" @click="queding">
					确认
				</view>
			</view>
			<picker-view :indicator-style="indicatorStyle" immediate-change="true" :value="valuedate"
				@change="bindChange" class="picker-view" v-if="popuStr=='就诊日期'">
				<picker-view-column>
					<view class="item" v-for="(item,index) in years" :key="index">{{item}}年</view>
				</picker-view-column>
				<picker-view-column>
					<view class="item" v-for="(item,index) in months" :key="index">{{item}}月</view>
				</picker-view-column>
				<picker-view-column>
					<view class="item" v-for="(item,index) in days" :key="index">{{item}}日</view>
				</picker-view-column>
			</picker-view>
			<picker-view immediate-change="true" v-if="popuStr=='就诊类型'" :indicator-style="indicatorStyle"
				:value="value1" @change="bindChange" class="picker-view">
				<picker-view-column>
					<view class="item" v-for="(item,index) in arr" :key="index">{{item.name}}</view>
				</picker-view-column>
			</picker-view>
		</up-popup>
		<view class="" style="height: 230rpx;">

		</view>
		<view class="fixed">
			<view class="btn" @click="savebc">
				保存病程
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		baseUrl
	} from '@/ulm/config';
	const indicatorStyle = ref(`height: 50px;`)
	import headertop from '@/components/header.vue'
	import {
		_static
	} from '@/ulm/utils/url.js'
	import {
		ref,
		reactive,
		onMounted
	} from 'vue'
	import {
		onPageScroll,
		onLoad,
		onShow,
		onReachBottom
	} from "@dcloudio/uni-app";
	import {
		getToken
	} from '@/ulm/utils/auth.js'
	import {
		$api
	} from '../../ulm';
	const popuStr = ref('')
	const date = new Date()
	const years = []
	const year = date.getFullYear()
	const months = []
	const month = date.getMonth() + 1
	const days = []
	const day = date.getDate()
	const valuedate = ref([9999, month - 1, day - 1])
	for (let i = 1900; i <= date.getFullYear(); i++) {
		years.push(i)
	}
	for (let i = 1; i <= 12; i++) {
		months.push(i)
	}
	for (let i = 1; i <= 31; i++) {
		days.push(i)
	}
	const pagetitle = ref('')
	const statusBarHeight = ref('')
	const texts = ref('')
	const barHeight = ref('')
	const back1 = ref('')
	const active = ref(2)
	const value1 = ref(0)
	const show = ref(false)
	const medicine_images = ref([])
	const formData = reactive({
		id: undefined,
		is_first: undefined,
		visit_time: '',
		hospital: '',
		diagnosis_result: '',
		zhusu: '',
		xianbingshi: '',
		jiwangshi: '',
		images: '',
		medicine_images: '',
		remark: ''
	})
	const visit_time = ref('')
	const images = ref([])
	const is_firstval = ref('')
	const arr = reactive([{
		'name': '初诊',
		id: 1
	}, {
		'name': '复诊',
		id: 2
	}])
	onLoad((opt) => {
		if (opt.id) {
			pagetitle.value = '编辑病程'
			inithuoqu(opt.id)
		} else {
			pagetitle.value = '添加病程'
		}
	})
	async function inithuoqu(id) {
		const res = await $api.medicalRecordDetail({
			id
		})
		if (res.code == 1) {
			formData.is_first = res.data.is_first
			formData.visit_time = res.data.visit_time
			formData.hospital = res.data.hospital
			formData.diagnosis_result = res.data.diagnosis_result
			formData.zhusu = res.data.zhusu
			formData.xianbingshi = res.data.xianbingshi
			formData.jiwangshi = res.data.jiwangshi
			images.value = res.data.images || []
			if (!res.data.medicine_images) {
				medicine_images.value = []
			} else {
				medicine_images.value = res.data.medicine_images
			}
			formData.remark = res.data.remark
			formData['id'] = res.data.id
		}
	}
	onMounted(() => {
		statusBarHeight.value = uni.getSystemInfoSync().statusBarHeight
		const {
			top,
			height
		} = wx.getMenuButtonBoundingClientRect();
		barHeight.value = height ? height + (top - statusBarHeight.value) * 2 : 38;
	})
	onPageScroll((e) => {
		if (e.scrollTop > 100) {
			back1.value = '#81D6FF'
		} else {
			back1.value = ''
		}
	})

	function open(str) {
		popuStr.value = str
		show.value = true
	}
	async function savebc() {
		if (!formData['is_first'] || !formData.visit_time || !formData.diagnosis_result) {
			uni.showToast({
				title: '必填项不能为空',
				icon: 'none'
			})
			return
		}
		if (images.value.length) {
			formData.images = images.value.join()
		}
		if (medicine_images.value.length) {
			formData.medicine_images = medicine_images.value.join()
		}

		if (pagetitle.value == '编辑病程') {
			const res1 = await $api.editMedicalRecord(formData)
			if (res1.code == 1) {
				setTimeout(function() {
					uni.showToast({
						title: '保存成功',
						icon: 'none'
					})
				}, 500);
				uni.navigateBack();
			} else {
				uni.showToast({
					title: res1.msg,
					icon: 'none'
				})
			}
			return
		}

		const res = await $api.addMedicalRecord(formData)
		if (res.code == 1) {
			setTimeout(function() {
				uni.showToast({
					title: '保存成功',
					icon: 'none'
				})
			}, 500);
			uni.navigateBack();
		} else {
			uni.showToast({
				title: res.msg,
				icon: 'none'
			})
		}
	}

	function convertToTimestamp(dateStr) {
		return new Date(dateStr).getTime();
	}


	function uploadImage(str) {
		var countnum = 0
		if (str == 'images') {
			countnum = 3 - images.value.length
		} else {
			countnum = 3 - medicine_images.value.length
		}
		uni.chooseImage({
			count: countnum, // 最多可选择图片数量
			sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图
			sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机
			success: (res) => {
				const validImages = res.tempFiles.filter(file => {
					return file.size <= 2 * 1024 * 1024; // 2MB = 2 * 1024 * 1024 Bytes
				});
				if (validImages.length === 0) {
					uni.showToast({
						title: `${res.tempFiles.length - validImages.length}张图片超过2MB`,
						icon: 'none'
					});
					return;
				}
				// tempFilePath 可以作为 img 标签的 src 属性显示图片
				const tempFilePaths = res.tempFilePaths
				uploadImages(tempFilePaths, str)
			},
			fail: (err) => {

			}
		})
	}

	function shanchu(arr, i) {
		arr.splice(i, 1)
	}

	function uploadImages(filePaths, str) {
		const uploadTasks = filePaths.map((filePath, index) => {
			return new Promise((resolve, reject) => {
				uni.uploadFile({
					url: `${baseUrl}/api/common/upload`,
					filePath: filePath,
					name: 'file',
					formData: {
						index: index // 可以添加序号标识
					},
					header: {
						token: getToken()
					},
					success: (uploadRes) => {
						resolve(JSON.parse(uploadRes.data))
					},
					fail: (err) => {
						reject(err)
					}
				})
			})
		})

		uni.showLoading({
			title: '上传中...'
		})

		Promise.all(uploadTasks)
			.then(results => {
				if (str == 'medicine_images') {
					for (var i in results) {
						medicine_images.value.push(results[i]['data']['fullurl'])
					}
				} else {
					for (var i in results) {
						images.value.push(results[i]['data']['fullurl'])
					}
				}
				uni.hideLoading()

				uni.showToast({
					title: `成功上传${results.length}张图片`,
					icon: 'success'
				})
			})
			.catch(err => {
				uni.hideLoading()

			})
	}

	function numtext(id) {
		var ind = arr.findIndex(item => item.id == id)
		if (ind == -1) {
			return ''
		} else {
			return arr[ind]['name']
		}
	}

	function bindChange(e) {
		const val = e.detail.value
		if (popuStr.value == '就诊类型') {
			is_firstval.value = arr[val[0]]['id']
		} else {
			visit_time.value =
				`${years[val[0]]}-${months[val[1]]<10?'0'+months[val[1]]:months[val[1]]}-${days[val[2]]<10?'0'+days[val[2]]:days[val[2]]}`
		}
	}

	function queding() {
		if (popuStr.value == '就诊类型') {
			if (!is_firstval.value) {
				formData['is_first'] = arr[0]['id']
			} else {
				formData['is_first'] = is_firstval.value
			}
		} else {
			if (!visit_time.value) {
				formData['visit_time'] =
					`${date.getFullYear()}-${months[month-1]<10?'0'+months[month-1]:months[month-1]}-${day<10?'0'+day:day}`
			} else {
				formData['visit_time'] = visit_time.value
				if (convertToTimestamp(formData['visit_time']) > Date.now()) {
					formData['visit_time'] = ''
					uni.showToast({
						title: '请选择正确就诊日期',
						icon: 'none'
					})
					return
				}
			}
		}
		show.value = false
	}
</script>

<style lang="scss">
	.rightarrow {
		width: 24rpx;
		height: 24rpx;
	}

	.picker-view {
		width: 100%;
		height: 600rpx;
		margin-top: 20rpx;
		background: #FFFFFF;
		border-radius: 20rpx 20rpx 0 0;
	}

	.xuanxiang {
		width: 100%;
		display: flex;
		align-items: center;
		margin-top: 30rpx;
		overflow: hidden;
		justify-content: space-between;
		margin-bottom: 30rpx;

		.tt {
			font-size: 32rpx;
		}
	}

	.item {
		line-height: 100rpx;
		text-align: center;
	}

	::v-deep .u-popup__content {
		border-radius: 20rpx 20rpx 0 0;
	}

	.fixed {
		width: 100%;
		height: 194rpx;
		background: #FFFFFF;
		box-shadow: 0rpx -6rpx 14rpx 0rpx rgba(0, 0, 0, 0.03);
		border-radius: 0rpx 0rpx 0rpx 0rpx;
		position: fixed;
		bottom: 0%;
		z-index: 9999;

		.btn {
			width: 686rpx;
			height: 82rpx;
			background: #2AB4F5;
			border-radius: 12rpx 12rpx 12rpx 12rpx;
			text-align: center;
			line-height: 82rpx;
			font-family: PingFang SC, PingFang SC;
			font-weight: 500;
			font-size: 32rpx;
			color: #FFFFFF;
			margin: auto;
			margin-top: 32rpx;
		}
	}

	page {
		background: #F7F8FA;
	}

	.addjiancha {
		width: 100%;
		overflow: hidden;

		.addjianchaback {
			width: 100%;
			height: 450rpx;
			background: linear-gradient(180deg, #CAEEFF 71%, rgba(240, 250, 255, 0) 100%);
			border-radius: 0rpx 0rpx 0rpx 0rpx;
			position: absolute;
			z-index: -1;
		}

		.jianchaxm {
			width: 686rpx;
			margin: auto;
			overflow: hidden;
			margin-top: 32rpx;

			.cardform {
				width: 100%;
				background: #FFFFFF;
				box-shadow: 0rpx 4rpx 10rpx 0rpx rgba(0, 0, 0, 0.03);
				border-radius: 24rpx 24rpx 24rpx 24rpx;
				overflow: hidden;
				padding: 8rpx 0;

				.center {
					width: 630rpx;
					overflow: hidden;
					margin: auto;

					.lineform {
						width: 100%;
						min-height: 88rpx;
						display: flex;
						align-items: center;
						justify-content: space-between;
						border-bottom: 2rpx solid #F2F3F5;

						.lefttext {
							font-family: PingFang SC, PingFang SC;
							font-weight: 400;
							font-size: 28rpx;
							color: #1D2129;
						}

						.textsform {
							width: 630rpx;
							border-radius: 16rpx 16rpx 16rpx 16rpx;
							height: 130rpx;
							background: #F7F8FA;
							overflow: hidden;
							margin-top: 24rpx;
							margin-bottom: 32rpx;
							padding: 24rpx;

							.text1 {
								font-size: 24rpx;
								height: 80rpx;
							}
						}

						.images {
							width: 100%;
							display: flex;
							align-items: center;
							flex-wrap: wrap;
							margin-top: 24rpx;

							.image {
								width: 224rpx;
								height: 174rpx;
								border-radius: 16rpx 16rpx 16rpx 16rpx;
								position: relative;
								margin-right: 30rpx;
								margin-bottom: 10rpx;

								image {
									width: 224rpx;
									height: 174rpx;
									border-radius: 16rpx 16rpx 16rpx 16rpx;
									overflow: hidden;
								}

								.remivon {
									position: absolute;
									width: 30rpx;
									height: 30rpx;
									top: -6%;
									right: -6%;
									z-index: 9999;
								}
							}

							.imageadd {
								width: 224rpx;
								height: 174rpx;
								border-radius: 16rpx 16rpx 16rpx 16rpx;
								margin-right: 30rpx;
								margin-bottom: 10rpx;
							}

						}

						.msgtext {
							font-family: PingFang SC, PingFang SC;
							font-weight: 400;
							font-size: 24rpx;
							color: #86909C;
							margin-top: 16rpx;
							margin-bottom: 24rpx;
						}

						.rightcontent {
							display: flex;
							align-items: center;

							.righticon {
								width: 32rpx;
								height: 30rpx;
								margin-right: 4rpx;
							}

							input {
								text-align: right;
								font-size: 28rpx;
							}
						}
					}
				}
			}
		}
	}
</style>